<!-- 商品列表 -->
<template>
  <div class="container">
    <div class="search-container">
      <el-input v-model="search" size="small" placeholder="请输入商品名称搜索" style="width: 200px;" clearable>
        <template #prefix>
          <el-icon>
            <Search />
          </el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="showAddGoodDialog" style="margin-left: 16px;">
        添加新商品
      </el-button>
    </div>

    <el-scrollbar>
      <el-table v-loading="loading" :data="filterTableData1" style="width: 100%" @row-click="handleRowClick"
        height="700">
        <el-table-column prop="productId" label="商品ID" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.productId }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名称" style="color: black" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="ellipsis">
              <el-input v-if="row.isEdit && row.isDelete == '0'" v-model="row.name" size="small"></el-input>
              <span v-else>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="商品价格" show-overflow-tooltip>
          <template #default="{ row }">
            <el-input v-if="row.isEdit && row.isDelete == '0'" v-model="row.price" size="small"></el-input>
            <span v-else>{{ row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="商品描述" show-overflow-tooltip>
          <template #default="{ row }">
            <el-input v-if="row.isEdit && row.isDelete == '0'" v-model="row.description" size="small"></el-input>
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="image" label="图片">
          <template #default="{ row }">
            <div v-if="row.isEdit && row.isDelete == '0'" class="avatar-uploader">
              <el-upload class="avatar-uploader" action="#" :auto-upload="false" :show-file-list="false"
                :on-change="(file) => handleAvatarChange(file.raw, row)">
                <img v-if="row.image" :src="row.imageFile ? row.image : 'http://localhost:8081' + row.image"
                  class="avatar" style="width: 50px; height: 50px" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </div>
            <img v-else :src="row.image ? 'http://localhost:8081' + row.image : ''" alt="商品图片"
              style="width: 50px; height: 50px" />
          </template>
        </el-table-column>
        <el-table-column prop="monthlySales" label="月销">
          <template #default="{ row }">

            <span>{{ row.monthlySales }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="isDelete" label="是否销售" show-overflow-tooltip>
          <template #default="{ row }">
            <el-select v-if="row.isEdit" v-model="row.isDelete" size="small">
              <el-option label="销售" value="0"></el-option>
              <el-option label="不销售" value="1"></el-option>
            </el-select>
            <span v-else>{{ row.isDelete === '0' ? '销售' : '不销售' }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button v-if="!row.isEdit" type="primary" @click="editRow(row)">
              修改
            </el-button>
            <el-button v-else type="success" @click="saveRow(row)">
              保存
            </el-button>
            <el-button v-if="row.isEdit" @click="cancelEdit(row)">取消</el-button>
            <el-button v-if="!row.isEdit" type="danger" @click="deleteRow(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 当没有数据时显示提示信息 -->
      <el-empty v-if="!loading && (!productList || productList.length === 0)" description="暂无数据" />

      <!-- 添加分页组件 -->
      <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
        :page-sizes="[8, 16, 32, 64]" :total="pagination.total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next" class="pagination" />
    </el-scrollbar>

    <AddGood ref="addGoodRef"></AddGood>
  </div>
</template>

<script setup>
import { h } from 'vue'
import { onMounted, ref, computed } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from "axios";
import { Search } from '@element-plus/icons-vue'
import AddGood from './AddGood.vue'
import { useProductStore } from '../stores/productStore'
import { storeToRefs } from 'pinia'

const productStore = useProductStore()
const { productList, pagination, loading } = storeToRefs(productStore)

const editRow = (row) => {
  row.originalName = row.name;
  row.originalPrice = row.price;
  row.originalDescription = row.description;
  row.originalImage = row.image;
  row.originalIsDelete = row.isDelete;
  row.isEdit = true;
};
const deleteRow = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该商品吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        message: h('p', null, [
          h('span', null, '删除后：\n'),
          h('br'),
          h('span', { style: 'color: red' }, '- 该商品将不再显示\n'),
          h('br'),
          h('span', { style: 'color: red' }, '- 相关的优惠券将被删除\n'),
          h('br'),
          h('span', { style: 'color: red' }, '- 历史订单中的商品信息将保留'),
        ]),
      }
    )

    const response = await axios.post('/deleteGood',
      row.productId,
      {
        headers: {
          'Content-Type': 'application/json',
          Authorization: sessionStorage.getItem('Authorization')
        }
      }
    )
    if (response.data.status === 200) {
      ElMessage.success(response.data.message);
      productList.value = productList.value.filter(good => good.productId !== row.productId);
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    ElMessage.error('删除失败');
  }
};

const cancelEdit = (row) => {
  const index = productList.value.findIndex(item => item.productId === row.productId);
  if (index !== -1) {
    if (row.isNew) {
      productList.value.splice(index, 1);
    } else {
      productList.value[index] = {
        ...productList.value[index],
        name: row.originalName || row.name,
        price: row.originalPrice || row.price,
        description: row.originalDescription || row.description,
        image: row.originalImage || row.image,
        isDelete: row.originalIsDelete || row.isDelete,
        isEdit: false,
        imageFile: null
      };
    }
  }
};
const saveRow = async (row) => {
  try {
    // 如果有新的图片文件待上传
    if (row.imageFile) {
      const formData = new FormData();
      formData.append('file', row.imageFile);

      try {
        // 先上传图片
        const uploadResponse = await axios.post(
          `/uploadFiles/${row.productId}`,
          formData,
          {
            headers: {
              Authorization: sessionStorage.getItem("Authorization"),
              'Content-Type': 'multipart/form-data'
            }
          }
        );

        if (uploadResponse.data.status === 200) {
          row.image = '/res/images/' + uploadResponse.data.data;
        } else {
          ElMessage({
            message: '图片上传失败',
            type: 'error'
          });
          return;
        }
      } catch (uploadError) {
        ElMessage({
          message: '图片上传失败',
          type: 'error'
        });
        return;
      }
    }

    // 保存商品信息
    try {
      const response = await axios.post(
        "/updateGood",
        {
          productId: row.productId,
          name: row.name,
          price: row.price,
          description: row.description,
          image: row.image,
          monthlySales: row.monthlySales,
          typeId: row.typeId,
          isDelete: row.isDelete,
        },
        {
          headers: {
            Authorization: sessionStorage.getItem("Authorization"),
          },
        }
      );

      if (response.data.status === 200 || response.data.status === 500) {
        ElMessage({
          message: '保存成功',
          type: 'success'
        });
        row.isEdit = false;
        row.imageFile = null; // 清除临时件
      } else {
        ElMessage.error('保存失败');


      }
    } catch (saveError) {
      ElMessage({
        message: '保存失败',
        type: 'error'
      });
    }
  } catch (error) {
    ElMessage({
      message: '操作失败',
      type: 'error'
    });
  }
};

// 改图片选择处理函数
const handleAvatarChange = (file, row) => {
  if (beforeAvatarUpload(file)) {
    // 将文件暂存在行数据中
    row.imageFile = file;
    // 创建本地预览URL
    row.image = URL.createObjectURL(file);
  }
};

// ��传前的验证
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 6

  if (!isImage) {
    ElMessage.error('上传图片只能是图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不超过 6MB!')
    return false
  }
  return true
}

// 处理页码改变
const handleCurrentChange = async (val) => {
  await productStore.updatePagination({ current: val })
}

// 处理每页显示数量改变
const handleSizeChange = async (val) => {
  await productStore.updatePagination({ current: 1, size: val })
}

// 修改模板中的分页组件绑定

// 修改 onMounted
onMounted(async () => {
  console.log('Component mounted, fetching data...') // 添加调试日志
  await productStore.fetchProductList()
});

const search = ref(""); // 响应式搜索变量
// 计算属性，根据搜索值过滤用户列表
const filterTableData1 = computed(() => {
  if (!search.value) {
    return productList.value;
  }
  return productList.value.filter(
    (good) => good.name.toLowerCase().includes(search.value.toLowerCase())
  );
});

// 添加对话框相关方法
const addGoodRef = ref(null)
const showAddGoodDialog = () => {
  addGoodRef.value.dialogVisible = true
}


</script>
<style scoped>
.pagination {

  display: flex;
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 垂直居中 */
}

.container {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.search-container {
  width: 100%;
  padding: 20px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  /* 使搜索框和按钮垂直居中对齐 */
}

.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}

.el-input {
  margin-right: 10px;
}
</style>